package com.googlecode.tapestry5validator.hibernate.adapters;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;

import org.hibernate.validator.Pattern;

public class PatternAdapter extends ParametersToJsonAdapter {

	@Override
	public Class<? extends Annotation> getAnnotationClass() {
		return Pattern.class;
	}

	@Override
	public String getJSMethod() {
		return "hvPattern";
	}

	@Override
	public String getValidatorType() {
		return "hv-pattern";
	}


	@Override
	public String fetchToJSParametrs(Map<String, Object> annotationParameters) {
		Map<String, Object>	params = new HashMap<String, Object>(annotationParameters);
		
		String jsFlags = "";
		
		int flags = (Integer) annotationParameters.get("flags");
		
		if (has(flags, java.util.regex.Pattern.CASE_INSENSITIVE)) {
			jsFlags += "i";
		}
		
		if (has(flags, java.util.regex.Pattern.MULTILINE)) {
			jsFlags += "m";
		}
		
		params.put("flags", jsFlags);
		
		return super.fetchToJSParametrs(params);
	}

    private boolean has(int flags, int f) {
        return (flags & f) != 0;
    }

	public static void main(String[] args) {
		java.util.regex.Pattern pattern = 
			java.util.regex.Pattern.compile("\\w{3}mar\\w{3}");

		                          	
  		String string = "submarine";
  		Matcher m = pattern.matcher( string );
  		System.out.println(m.matches());
	}
	
}
